<template>
    <div class="user-list-container custom-scrollbar">
        <h3>用户列表</h3>
        <div class="filter flex">
            <el-input v-model="userListParams.name" placeholder="用户名"/>
            <el-button type="primary" @click="handleSearch()">搜索</el-button>
            <!--            <el-button :disabled="commonData.challengeLoading" type="primary" @click="handleSearch()">随机挑战</el-button>-->
        </div>
        <el-table v-loading="commonData.loading" border ref="tableRef" row-key="date" :data="commonData.tableData"
                  style="width: 100%">
            <el-table-column prop="name" label="用户名"/>
            <el-table-column
                    prop="url"
                    label="头像">
                <template #default="scope">
                    <el-avatar v-if="scope.row.url" size="30" :src="scope.row.url"/>
                    <el-avatar v-else size="30" :icon="UserFilled"/>
                </template>
            </el-table-column>
            <el-table-column prop="score" label="积分"/>
            <el-table-column
                    label="状态"
            >
                <template #default="scope">
                    <el-tag v-if="scope.row.state===0" class="ml-2" type="danger">离线</el-tag>
                    <el-tag v-else class="ml-2" type="success">在线</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="注册时间"/>
            <el-table-column
                    label="操作"
            >
                <template #default="scope">
                    <el-button v-if="scope.row.state===1" :disabled="commonData.challengeLoading"
                               v-loading="commonData.challengeLoading"
                               type="primary"
                               @click="handleChallenge(scope.row.id)">发起挑战
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination-box flex justify-content-flex-end">
            <el-pagination
                    :hide-on-single-page="true"
                    :current-page="userListParams.page"
                    :page-size="pagination.pageSize"
                    background
                    layout="prev, pager, next, jumper"
                    :total="pagination.total"
                    @current-change="handleCurrentChange"
            />
        </div>
        <cbl-message-box :info="messageBoxInfo"></cbl-message-box>
    </div>
</template>

<script setup>
    import {UserFilled} from '@element-plus/icons-vue';
    import CblMessageBox from '@/components/CblMessageBox.vue';
    import {reactive, onMounted, onBeforeUnmount, getCurrentInstance, ref} from 'vue';
    import {api} from '@/utils/config';
    import service from '@/utils/service';
    import {ElMessage} from 'element-plus';
    import {useRouter} from 'vue-router';

    const {proxy} = getCurrentInstance();
    const router = useRouter();

    const timer = ref(null);//计时器
    let times = ref(20);//倒计时20s
    let firstChallenge = ref('');//挑战的用户
    const userListParams = reactive({
        page: 1,
        name: ''
    });
    //弹框信息
    const messageBoxInfo = reactive({
        title: '挑战信息',
        content: `您正在发起挑战，${times.value}s后自动关闭，默认对方拒绝挑战`,
        show: false,
        showCancelBtn: false,
        showConfirmBtn: false
    });
    const commonData = reactive({
        loading: true,
        challengeLoading: false,
        tableData: []
    });
    const pagination = reactive({
        total: 0,
        pageSize: 10
    });
    const socket = {
        //发起挑战的接口
        async challengeResult(data) {
            times.value = 20;
            window.clearTimeout(timer.value);
            timer.value = null;
            messageBoxInfo.show = false;
            messageBoxInfo.content = `您正在发起挑战，${times.value}s后自动关闭，默认对方拒绝挑战`;
            if (data.code === 0) {
                ElMessage({
                    showClose: false,
                    message: data.msg,
                    type: 'error',
                });
                commonData.challengeLoading = false;
            } else {
                await router.push('/index/chess');
            }
        },
        //检查在线用户
        checkOnlineUser(data) {
            console.log(data);
            for (let i = 0; i < commonData.tableData.length; i++) {
                if (data.indexOf(commonData.tableData[i].id.toString()) >= 0) {
                    commonData.tableData[i].state = 1;
                } else {
                    commonData.tableData[i].state = 0;
                }
            }
        }
    };
    onMounted(() => {
        proxy.$addSockets(socket, proxy);
        getUserList();
    });
    onBeforeUnmount(() => {
        proxy.$removeSockets(socket, proxy);
    });
    //发起挑战
    const handleChallenge = (id) => {
        console.log(id);
        firstChallenge.value = id;
        proxy.$socket.io.emit('sendChallenge', id);
        commonData.challengeLoading = true;
        messageBoxInfo.content = `您正在发起挑战，${times.value}s后自动关闭，默认对方拒绝挑战`;
        messageBoxInfo.show = true;
        handleTimer();
    };
    //获取用户列表
    const getUserList = () => {
        commonData.loading = true;
        service.doGet(api['list'], userListParams)
            .then(async (response) => {
                if (response.code === 1) {
                    const data = response.data;
                    for (let i = 0; i < data.list.length; i++) {
                        data.list[i]['state'] = 0;
                    }
                    commonData.tableData = data.list;
                    pagination.total = data.count;
                    proxy.$socket.io.emit('checkOnlineUser');
                }
                commonData.loading = false;
            }).catch(() => {
            commonData.loading = false;
        })
    };
    //切换分页
    const handleCurrentChange = (data) => {
        userListParams.page = data;
        getUserList();
    };
    //搜索按钮
    const handleSearch = () => {
        userListParams.page = 1;
        getUserList();
    };
    //处理计时器
    const handleTimer = () => {
        timer.value = window.setTimeout(function () {
            if (times.value <= 0) {
                times.value = 20;
                timer.value = null;
                messageBoxInfo.show = false;
                commonData.challengeLoading = false;
            } else {
                times.value--;
                messageBoxInfo.content = `您正在发起挑战，${times.value}s后自动关闭，默认对方拒绝挑战`;
                handleTimer();
            }
        }, 1000);
    };
</script>

<style scoped lang="less">
    .user-list-container {
        height: 100%;
        background: #fff;
        padding: 15px;
        overflow: auto;
        box-sizing: border-box;

        .filter {
            margin-bottom: 15px;

            input {
                max-width: 200px;
            }

            .el-input {
                max-width: 200px;
                margin-right: 15px;
            }
        }

        .pagination-box {
            margin-top: 20px;
            text-align: right;
        }
    }
</style>